<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="mySchema" v-slot="{errors}">
    <!-- QQ用户信息 -->
    <div class="user-info">
      <img :src=avatar>
      <p>Hi，{{nickname}}，欢迎来小兔鲜，完成绑定后可以使用QQ账号一键登录哦~</p>
    </div>
    <!-- 绑定手机号的表单 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" v-model="form.mobile" name="mobile" class="input" type="text" placeholder="请输入要绑定的手机号"/>
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
    </div>
    <!-- 验证码 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" v-model="form.code" name="code" class="input" type="text" placeholder="短信验证码"/>
        <span class="code" @click="send()">{{time===0?'发送验证码':`${time}秒后再发送`}}</span>
      </div>
      <div v-if="errors.code" class="error">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit()">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { ref, reactive, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: { Form, Field },
  setup (props) {
    // 用户头像和昵称
    const nickname = ref('null')
    const avatar = ref('null')
    // 1.openid（后台需要的unionid 从父组件中传）、QQ头像和昵称
    // 2.表单校验
    // 3.发送验证码（先校验、再调api、开启倒计时）
    // 4.进行绑定（绑定成功=登录成功）
    // 拿到QQ登录的信息
    if (QC.Login.check()) {
      // 1.获取用户头像和昵称
      QC.api('get_user_info').success(res => {
        nickname.value = res.data.nickname
        avatar.value = res.data.figureurl_1
      })
    }
    // 定义校验规则对象、表单对象
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }
    const form = reactive({
      mobile: null,
      code: null
    })

    // 发送短信验证码
    const time = ref(0)
    const formCom = ref(null)
    const { pause, resume } = useIntervalFn(() => {
      // 回调函数 时间减少到0时就停止定时器
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })

    onUnmounted(() => {
      pause()
    })
    // 发送短信
    const send = async () => {
      // console.log('已经点击')
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        // console.log('通过验证')
        // console.log(time.value)
        // 没有倒计时才可以发送
        if (time.value === 0) {
          // console.log('没有定时器')
          // console.log(userAccountLoginMsg(form.mobile))
          await userQQBindCode(form.mobile)
          Message({ type: 'success', text: '短信验证码已发送' })
          time.value = 60
          // 开始定时器
          // console.log(time.value)
          resume()
        }
      } else {
        // 失败 使用vee的错误函数setFieldError(字段名称，错误信息)显示错误信息
        formCom.value.setFieldError('mobile', valid)
      }
    }

    // 立即绑定
    const store = useStore()
    const router = useRouter()
    const submit = () => {
      const valid = formCom.value.validate()
      if (valid) {
        userQQBindLogin({
          unionId: props.unionId,
          ...form
        }).then(data => {
          // 实现和之前登录一样的逻辑
          const { id, account, avater, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avater, mobile, nickname, token })
          store.dispatch('cart/mergeCart').then(() => {
            // 2.跳转到来源页或者首页（已经在vuex中保存的回跳地址）
            router.push(store.state.user.redirectUrl)
            // 3.提示信息
            Message({ type: 'success', text: 'QQ绑定成功' })
          })
        }).catch(e => {
          console.log(e)
          Message({ type: 'error', text: '绑定失败' })
        })
      }
    }
    return { nickname, avatar, form, mySchema, time, send, formCom, submit }
  }
}
</script>

<style lang="less" scoped>
.user-info{
  width: 320px;
  height: 70px;
  margin: 0 auto;
  align-items: center;
  display: flex;
  padding-left:400px ;
  background-color: #f2f2f2;
  padding: 0 10px;
  margin-bottom: 25px;
  img{
    background-color: #f2f2f2;
    width: 50px;
    height: 50px;
    border: 1px solid #fff;
  }
  p{
    padding-left: 10px;
  }
}
.code{
  position: absolute;
  right:0;
  top:0;
  line-height: 50px;
  width: 97px;
  color:#999;
  text-align: right;
  padding-right :10px;
  &:hover{
    cursor: pointer;
  }
}
</style>
